# @Time    :2025/4/7 19:56
"""
 加锁 解决线程安全问题

lock = threading.Lock()  # 创建一个锁对象
lock.acquire()  # 获取锁
lock.release()  # 释放锁
"""
import threading
import time




def func():
    global g_num
    for _ in range(10):
        # 获取锁
        lock.acquire()
        try:
            tmp = g_num + 1
            time.sleep(0.3)
            g_num = tmp
            print(f"当前线程{threading.current_thread().name}:{g_num}")
        finally:
            # 释放锁
            lock.release()


if __name__ == "__main__":
    # 定义一个全局变量
    g_num = 0
    lock = threading.Lock()
    threads = [threading.Thread(target=func, name="线程" + str(i)) for i in range(3)]
    [t.start() for t in threads]
    [t.join() for t in threads]
    # 上面的列表推导式 等价于下边这种写法
    # for t in threads:
    #     t.start()
    print(f"当前线程{threading.current_thread().name}", g_num)
